package net.lzzy.practices.web.course;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import net.lzzy.practices.constants.ApiConstants;
import net.lzzy.practices.constants.Messages;
import net.lzzy.practices.services.ResultService;
import net.lzzy.practices.utils.StringUtils;
import net.lzzy.practices.web.models.ApiResult;
import net.lzzy.practices.web.models.VmResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * @author  Jaymo on 2022/6/8
 */
@CrossOrigin
@RestController
@RequestMapping(ApiConstants.ROUTE_RESULT_ROOT)
public class ResultApiController {
    private  final ResultService service;

    @Autowired
    public  ResultApiController(ResultService service){
        this.service = service;
    }

    @PostMapping(ApiConstants.ROUTE_RESULT_POST)
    public ApiResult postResult(@RequestBody JSONObject json){
        String token = json.getString(ApiConstants.KEY_TOKEN);
        if (StringUtils.isEmpty(token)){
            return  new ApiResult(false, Messages.No_PERMISSION.toString(), null);

        }
        JSONArray array = json.getJSONArray(ApiConstants.KEY_RESULT_OPTION_ARRAY);
        if (array == null){
            return  new ApiResult(false,Messages.INCOMPLETE_INFO.toString(),null);
        }
        List<VmResult> results = new ArrayList<>();
        for (int i = 0; i < array.size(); i++) {
            JSONObject jo = array.getJSONObject(i);
            String strQuestionId = jo.getString(ApiConstants.KEY_RESULT_OPTION_QUESTION_ID);
            JSONArray arrOptions = jo.getJSONArray(ApiConstants.KEY_RESULT_OPTION_ID);
            UUID questionId = UUID.fromString(strQuestionId);
            List<UUID> optionIds = new ArrayList<>();
            arrOptions.forEach(o -> optionIds.add(UUID.fromString(o.toString())));
           results.add(new VmResult(service.add(questionId,optionIds,token)));
        }
        return  new ApiResult(true, results.size() + "", results);
    }
}
